package com.pap.oauth.config.exception.oauth;

import com.pap.obj.vo.response.ResponseVO;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.*;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 定制 BadCredentialsException,UserNameNotFound 的异常消息
 * 自定义异常转换器
 *
 * 在 OAuth2Config.config(AuthorizationServerEndpointsConfigurer endpoints) 中 增加
 *          endpoints.exceptionTranslator(PapSecurityWebResponseExceptionTranslator)
 */
@Component
public class PapSecurityOauth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        ResponseVO<OAuth2AccessToken> response = new ResponseVO<OAuth2AccessToken>();
        response.setCode("600");
        if(e instanceof InvalidRequestException) {
            InvalidRequestException invalidRequestException = (InvalidRequestException)e;
            response.setMsg(invalidRequestException.getMessage());
        }
        if(e instanceof InvalidGrantException) {
            InvalidGrantException invalidGrantException = (InvalidGrantException)e;
            response.setMsg(invalidGrantException.getMessage());
        }
        if(e instanceof RedirectMismatchException) {
            RedirectMismatchException redirectMismatchException = (RedirectMismatchException)e;
            response.setMsg(redirectMismatchException.getMessage());
        }
        if(e instanceof InvalidClientException) {
            InvalidClientException invalidClientException = (InvalidClientException)e;
            response.setMsg(invalidClientException.getMessage());
        }
        if(e instanceof InternalAuthenticationServiceException) {
            InternalAuthenticationServiceException internalAuthenticationServiceException = (InternalAuthenticationServiceException)e;
            response.setMsg(internalAuthenticationServiceException.getMessage());
        }
        return ResponseEntity.status(200).body(response);
    }

}